package com.bang.concurrency.example.syncContainer;

import com.bang.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Hashtable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Auther: Bang
 * @Date: 2019/10/1 20:00
 * @Description:
 */
@Slf4j
@ThreadSafe
public class HashTableExample {

    // 请求数量
    private static int clientCount = 5000;

    // 线程数量
    private static int threadCount = 200;

    private static Hashtable<Integer, Integer> map = new Hashtable<>();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadCount);
        final CountDownLatch countDownLatch = new CountDownLatch(clientCount);
        for (int i = 0; i < clientCount; i++) {
            final int count = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update(count);
                    semaphore.release();
                    countDownLatch.countDown();
                } catch (Exception e) {
                    log.error("Error : {}", e);
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.error("size = {}", map.size());
    }

    private static void update(int count) {
        map.put(count, count);
    }
}
